package cn.tedu.micro.demo.rabbit.controller;

import cn.tedu.micro.demo.rabbit.amqp.AmqpDelayProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * 在控制层 注入现成的对象RabbitTemplate
 * 调用其API方法将消息封装 发送到目的地(交换机)direct_demo_ex demo_rk
 */
@RestController
@Slf4j
public class SendController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpDelayProducer amqpDelayProducer;
    /**
     * GET 请求
     * /send
     * String msg 发送的消息
     * "ok"
     */
    @GetMapping("/send")
    public String send(String msg){
        //channel.basicPublish
        //调用rabbitmq的客户端封装模版
        //1.组织一个消息对象 包含消息体 消息属性
        //1.1消息体 byte[]
        byte[] body=msg.getBytes(StandardCharsets.UTF_8);
        //1.2消息属性
        MessageProperties properties=new MessageProperties();
        properties.setPriority(1000);
        Message message = new Message(body, properties);
        //2.调用api发送
        rabbitTemplate.send("direct_demo_ex","demo_rk",message);
        return "ok";
    }
    @GetMapping("/send/delay")
    public String sendDelay(String msg){
        //调用api发送延迟消息
        amqpDelayProducer.sendDelay("delay_ex",msg,10000);
        log.info("发送延迟消息成功,延迟时间 10 秒");
        return "ok";
    }
}